package wang.aweb.childcar.controller.api;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import wang.aweb.childcar.common.ApiRestResponse;
import wang.aweb.childcar.common.Constant;
import wang.aweb.childcar.model.req.WechatLoginReq;
import wang.aweb.childcar.service.MemberService;
import wang.aweb.childcar.util.WechatReqUtils;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/user/")
public class UserController {
    @Autowired
    private MemberService memberService;
    @Value("${userapp.appid}")
    private String appid;
    @Value("${userapp.secret}")
    private String appsecret;
    /**
     * 登录
     * @return
     */
    @ApiOperation("用户登录")
    @PostMapping("login")
    public ApiRestResponse login(@RequestBody WechatLoginReq wechatLoginReq) throws UnsupportedEncodingException {
        JSONObject resJson=WechatReqUtils.getOpenIdByCode(wechatLoginReq.getCode(),this.appid,this.appsecret);
        resJson.get("openid");
        Integer userId=memberService.doLogin(resJson.get("openid").toString(),wechatLoginReq.getInviteCode());
        Algorithm algorithm=Algorithm.HMAC256(Constant.JWT_KEY);
        String token= JWT.create()
                .withClaim(Constant.USER_ID,userId)
                .withClaim(Constant.USER_ROLE,1)
                .withExpiresAt(new Date(System.currentTimeMillis()+Constant.EXPIRE_TIME))
                .sign(algorithm);
        Map<String,String> tokenMap=new HashMap<>();
        //        session.setAttribute(Constant.MALL_USER,user);
        tokenMap.put("token",token);
        return ApiRestResponse.success(tokenMap);
    }
    @PostMapping("checkIsReady")
    public ApiRestResponse checkIsReady(){
        Map map=memberService.checkIsReady();
        return ApiRestResponse.success(map);
    }
}
